package com.asd.map.controller;

import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.asd.common.Result;
import com.asd.config.IdGenerator;
import com.asd.map.entity.*;
import com.asd.map.entity.vo.LineSurfaceVo;
import com.asd.map.entity.vo.Line_surfaceVo;
import com.asd.map.service.IInformationService;
import com.asd.map.service.ILine_surfaceService;
import com.asd.system.entity.ExcelFilesModel;
import com.asd.system.entity.User;
import com.asd.system.service.IImagesService;
import com.asd.system.service.IUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @createtime 2021-10-11 10:06
 * @description
 */

@Api(tags = "线面Api")
@RestController
@RequestMapping("/api/line_surface")
public class Line_surfaceController {

    @Autowired
    private ILine_surfaceService line_surfaceService;

    @Autowired
    private IInformationService iInformationService;

    @Autowired
    private IImagesService imagesService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IdGenerator idGenerator;


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "线面-通过id删除", notes = "线面-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {

        line_surfaceService.removeById(id);


        return Result.ok("删除成功!");
    }

    /**
     * 新增点位信息
     *
     * @return
     */
    @ApiOperation(value = "线面-添加", notes = "线面-添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "primaryEchoPath", value = "主图片回显地址"),
            @ApiImplicitParam(name = "viceEchoPathlist", value = "副主图片回显地址")
    })
    @PostMapping(value = "/addLine_surface")
    public Result<?> add1(@RequestBody Line_surface line_surface,
                          @RequestParam("primaryEchoPath") String primaryEchoPath,
                          @RequestParam("viceEchoPathlist") List<String> viceEchoPathlist) {

        String id = idGenerator.nextId();

        line_surface.setId(id);

        line_surfaceService.save(line_surface);

        if (!(primaryEchoPath.equals(null) || primaryEchoPath.equals(""))) {
            imagesService.updateByPrimaryEchoPath(id, primaryEchoPath);
        }
        if (viceEchoPathlist.size() > 0) {
            for (int i = 0; i < viceEchoPathlist.size(); i++) {
                String viceEchoPath = viceEchoPathlist.get(i);
                imagesService.updateByViceEchoPath(id, viceEchoPath);
            }
        }

        Line_surfaceVo line_surfaceVo = line_surfaceService.findById(id);

        return Result.ok(line_surfaceVo);
    }


    /**
     * 编辑
     *
     * @param
     * @return
     */
    @ApiOperation(value = "线面-编辑", notes = "线面-编辑")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "primaryEchoPath", value = "主图片回显地址"),
            @ApiImplicitParam(name = "viceEchoPathlist", value = "副主图片回显地址")
    })
    @PutMapping(value = "/update")
    public Result<?> edit(@RequestBody Line_surface line_surface,
                          @RequestParam("primaryEchoPath") String primaryEchoPath,
                          @RequestParam("viceEchoPathlist") List<String> viceEchoPathlist) {

        String id = line_surface.getId();


        Line_surface lineSurface = line_surfaceService.getById(id);

        if (!(line_surface.getLineSurfaces().equals(null) || line_surface.getLineSurfaces().equals(""))) {

            lineSurface.setLineSurfaces(line_surface.getLineSurfaces());
        }
        if (!(line_surface.getData().equals(null) || line_surface.getData().equals(""))) {
            lineSurface.setData(line_surface.getData());
        }
        if (!(primaryEchoPath.equals(null) || primaryEchoPath.equals(""))) {
            imagesService.updateByPrimaryEchoPath(id, primaryEchoPath);
        }
        if (viceEchoPathlist.size() > 0) {
            for (int i = 0; i < viceEchoPathlist.size(); i++) {
                String viceEchoPath = viceEchoPathlist.get(i);
                imagesService.updateByViceEchoPath(id, viceEchoPath);
            }
        }

        line_surfaceService.updateById(lineSurface);

        Line_surfaceVo line_surfaceVo = line_surfaceService.findById(id);

        return Result.ok(line_surfaceVo);

    }


    @ApiOperation(value = "根据did分页查询数据", notes = "根据did分页查询数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pagenum", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小"),
            @ApiImplicitParam(name = "did", value = "数据源id ", required = true),
    })
    @GetMapping("/findByDid")
    public Result<?> findByDid(@RequestParam(name = "pagenum", defaultValue = "1") Integer pagenum,
                               @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize,
                               @RequestParam(name = "did", required = true) String did) {

        Page<Line_surfaceVo> page = new Page<>(pagenum, pageSize);

        List<Line_surfaceVo> line_surfaceVoList = line_surfaceService.findByDid1(page, did);

//        page.setTotal(line_surfaceVoList.size());

        Page<Line_surfaceVo> pageList = page.setRecords(line_surfaceVoList);


        return Result.ok(pageList);
    }

    /**
     * 导入数据接口
     *
     * @return
     */
    @ApiOperation(value = "导入数据接口", notes = "导入数据接口")
    @PostMapping("/importExcel")
    public Result<?> importExcel(@RequestParam("userId") String userId,@RequestBody ExcelFilesModel excelFilesModel) throws JsonProcessingException {

        //新增数据源
        Information information = new Information();
        String id = idGenerator.nextId();
        information.setId(id);
        information.setIsImage(excelFilesModel.getIsImage());

        String str = excelFilesModel.getData();
        String data = str.replace(",经纬度", "");

        information.setData(data);

        information.setName(excelFilesModel.getName());
        information.setType(excelFilesModel.getType());
        iInformationService.save(information);



        //数据源绑定登录用户
        User user = userService.getById(userId);
//        //获取本用户所有的数据源id
        if (user.getDataInf() == null || user.getDataInf().equals("")) {
            List<String> list = new ArrayList<>();
            list.add(id);
            String str1 = JSON.toJSONString(list);
            user.setDataInf(str1);
            userService.updateById(user);

        } else {
            List<String> informationId = (List<String>) JSONArray.parse(user.getDataInf());
            informationId.add(id);
            String str1 = JSON.toJSONString(informationId);
            user.setDataInf(str1);
            userService.updateById(user);
        }


        //excel表中数据存入到数据库线面表
        String fileList = excelFilesModel.getFileList();

        if (!(fileList == null && fileList.equals(""))) {


            //将字符串转为List
            ObjectMapper mapper = new ObjectMapper();
            List<Map> list = mapper.readValue(fileList, List.class);



            for (int i = 0; i < list.size(); i++) {


                Map<String, Object> map = list.get(i);

//                String pointName = map.get("名称");

                ArrayList<Object> arrayList = new ArrayList<>();
                Line_surface line_surface = new Line_surface();


                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    Map<String, String> map1 = new HashMap<>();

                    if (entry.getKey().equals("名称")) {
                        map1.put("name", entry.getValue().toString());
                        map1.put("valueName", entry.getKey());
                        arrayList.add(map1);
                    } else if (!(entry.getKey().equals("经纬度"))) {
                        map1.put("value", entry.getValue().toString());
                        map1.put("valueName", entry.getKey());
                        arrayList.add(map1);
                    }


                }

//                String lng = map.get("经度").toString();
//                String lat = map.get("纬度").toString();

                String str1 = "[[";
                String str2 = "]]";


                String lineSurfaces = map.get("经纬度").toString();
                str1 += lineSurfaces;
                str1 += str2;

                String data1 = net.sf.json.JSONArray.fromObject(arrayList).toString();
                line_surface.setData(data1);

                line_surface.setDid(id);
                line_surface.setLineSurfaces(str1);

                line_surfaceService.save(line_surface);

            }
        }

        return Result.ok("导入成功");
    }


    @ApiOperation(value = "线面excel模板", notes = "线面excel模板")
    @GetMapping("/exportExcelTemplate")
    public void downDeviceManagementTemplate(HttpServletRequest req, HttpServletResponse res) throws IOException {


        String fileName = "线面示例数据" + ".xlsx";

        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("static/images/tables.xlsx");


        // 转为POI的Workbook输出流，这样下载后 打开不报错，直接输出  流 的话，打开excel可能提示错误
        @SuppressWarnings("resource")
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        String userAgent = req.getHeader("User-Agent");
        // 针对IE或者以IE为内核的浏览器：
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = URLUtil.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        res.setHeader("Content-disposition", "attachment; filename=" + fileName);
        res.setContentType("application/vnd.ms-excel; charset=utf-8");
        res.setCharacterEncoding("UTF-8");
        // 将流中内容写出去
        OutputStream outputStream = res.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }


    /**
     * 线面二次修改
     */
    @ApiOperation(value = "线面-二次修改", notes = "线面-二次修改")
    @PutMapping("/updateLineSurfaceModification")
    public Result<?> updateLineSurfaceModification(@RequestBody LineSurfaceVo lineSurfaceVo) {

        Result<User> result = new Result<User>();

        Line_surface line_surface = line_surfaceService.getById(lineSurfaceVo.getId());
        if (line_surface == null) {
            result.error500("未找到对应实体");
        } else {
            line_surface.setLineSurfaces(lineSurfaceVo.getLineSurfaces());
            boolean ok = line_surfaceService.updateById(line_surface);

            if (ok) {
                result.success("修改成功!");
            }

        }
        return result;
    }

    /**
     * 分页模糊查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "线面-分页模糊查询", notes = "线面-分页模糊查询")
    @GetMapping(value = "/list1")
    public Result<?> queryPageList1(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize,
                                    Line_surface line_surface) {


        Page<Line_surface> page = new Page<Line_surface>(pageNo, pageSize);

        IPage<Line_surface> pageList = line_surfaceService.selectPage(page, line_surface);

        return Result.ok(pageList);
    }



}
